package bbs;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.DB;
import util.RequestParameter;
import util.UnauthorizedAccessException;

import java.io.*;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/bbs/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestParameter param = new RequestParameter(request);
        int bid = param.getInt("bid", 0);
        int aid = param.getInt("aid", 0);
        try {
            Article article = ArticleDAO.selectById(aid);
            BoardService boardService = new BoardService(request, bid);
            if (boardService.canReadArticle(article))
                new UnauthorizedAccessException("게시글 보기 권한 없음");
        } catch (Exception e) {
            throw new ServletException(e);
        }

        String sql = "SELECT [fileName], [data] FROM bbs.[File] WHERE [id] = ?";
        try (Connection conn = DB.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            int ID = param.getInt("fid",  0);
            stmt.setInt(1, ID);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    String fileName = URLEncoder.encode(rs.getString("fileName"),"UTF-8");
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
                    Blob blob = rs.getBlob("Data");
                    try (InputStream input = blob.getBinaryStream();
                         BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream())) {
                        int count = 0;
                        byte buffer[] = new byte[2048];
                        while ((count = input.read(buffer)) != -1)
                            output.write(buffer, 0, count);
                    }
                }
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    public static String makeUrl(HttpServletRequest request, int boardId, int articleId, int fileId) {
        return String.format("%s/bbs/FileDownloadServlet?bid=%s&aid=%s&fid=%s",
                request.getContextPath(), boardId, articleId, fileId);
    }

}
